package com.duck.base.oauth.security.handler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.duck.base.oauth.security.model.HandlerModel;
import com.duck.base.response.BaseResponse;

/**
 * 登录失败返回的 JSON 格式数据
 * @author lwy
 *
 */
@Component
public class DuckAuthenticationFailureHandler implements AuthenticationFailureHandler {

	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {
		// TODO Auto-generated method stub
		BaseResponse<HandlerModel> baseResp = new BaseResponse<HandlerModel>();
		baseResp.setStatus("401.1");		
		if(exception instanceof BadCredentialsException) {
			baseResp.setMessage("密码错误");
		}else if (exception instanceof InternalAuthenticationServiceException) {
			baseResp.setMessage("用户不存在");
		}else {
			baseResp.setMessage(exception.getMessage());
		}
		response.getWriter().write(JSON.toJSONString(baseResp));
	}

}
